from django.db import models
from datetime import datetime
from django.db.models.query import QuerySet
from django.contrib.auth.models import BaseUserManager


class NaturalPersonMixin(object):

    def delete(self):
        for person in self:
            person.delete()


class NaturalPersonSet(NaturalPersonMixin, QuerySet):
    pass


class NaturalPersonManager(NaturalPersonMixin, models.Manager):
    def get_query_set(self):
        return NaturalPersonSet(self.model, using=self._db)


class CompanyMixin(object):

    def delete(self):
        for company in self:
            company.delete()


class CompanySet(CompanyMixin, QuerySet):
    pass


class CompanyManager(CompanyMixin, models.Manager):
    def get_query_set(self):
        return CompanySet(self.model, using=self._db)


class GroupManager(models.Manager):
    def get_by_natural_key(self, name):
        return self.get(name=name)


class UserManager(BaseUserManager):
    def create_user(self, email, password=None, **extra_fields):
        now = datetime.now()
        if not email:
            raise ValueError('The given email address must be set')
        email = UserManager.normalize_email(email)
        user = self.model(email=email,
                          is_staff=False, is_active=True, is_superuser=False,
                          last_login=now, date_joined=now, **extra_fields)

        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(self, email, password, **extra_fields):
        u = self.create_user(email, password, **extra_fields)
        u.is_staff = True
        u.is_active = True
        u.is_superuser = True
        u.save(using=self._db)
        return u
